package com.example.teacher.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.constants.OtherConstants;
import com.example.common.domain.pojo.Homework;
import com.example.common.domain.pojo.HomeworkStudent;
import com.example.common.domain.pojo.Student;
import com.example.common.domain.pojo.StudentAnswers;
import com.example.common.utils.UUIDUtil;
import com.example.teacher.Service.ClassesService;
import com.example.teacher.Service.HomeworkQuestionService;
import com.example.teacher.Service.HomeworkStudentService;
import com.example.teacher.Service.StudentService;
import com.example.teacher.domain.vo.HomeworkSatatus;
import com.example.teacher.domain.vo.HomeworkSatatusVo;
import com.example.teacher.domain.vo.StudentScoreVO;
import com.example.teacher.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HomeworkStudentServiceImpl extends ServiceImpl<HomeworkStudentMapper, HomeworkStudent> implements HomeworkStudentService {

    @Autowired
    private HomeworkStudentMapper homeworkStudentMapper;

    @Autowired
    private StudentMapper studentMapper;  // 假设存在学生Mapper
    @Autowired
    private StudentService studentService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private HomeworkStudentService homeworkStudentService;
    @Autowired
    private HomeworkQuestionService homeworkQuestionService;
    @Autowired
    private HomeworkQuestionMapper homeworkQuestionMapper;
    @Autowired
    private StudentAnswersMapper studentAnswersMapper;
    @Autowired
    private HomeworkMapper homeworkMapper;
    @Autowired
    private StudentAnswersMapper studentAnswerMapper; // 注入 StudentAnswerMapper


    @Override
    public HomeworkSatatus getHomeworkStatus(String homeworkId) {
        HomeworkSatatus status = new HomeworkSatatus();
        status.setHomeworkId(homeworkId);

        // 1. 查询该作业的总参与学生数
        LambdaQueryWrapper<HomeworkStudent> totalWrapper = new LambdaQueryWrapper<>();
        totalWrapper.eq(HomeworkStudent::getHomeworkId, homeworkId);
        Long totalStudents = homeworkStudentMapper.selectCount(totalWrapper);
        status.setTotalStudents(totalStudents);

        // 2. 查询完成人数（假设 isCompleted 为 true 表示完成）
        LambdaQueryWrapper<HomeworkStudent> completedWrapper = new LambdaQueryWrapper<>();
        completedWrapper.eq(HomeworkStudent::getHomeworkId, homeworkId)
                .or(wrapper -> wrapper
                        .like(HomeworkStudent::getStatus, "已完成")
                        .or() // 注意：这里的 or() 是为了让两个 like 也形成 OR 关系（可选，根据需求调整）
                        .like(HomeworkStudent::getStatus, "已评阅")
                )
                .isNotNull(HomeworkStudent::getStatus); // 关键修改：判断 status 非空
        Long completedCount = homeworkStudentMapper.selectCount(completedWrapper);
        status.setFinishNum(completedCount);

        // 3. 计算完成率（可选）
        if (totalStudents > 0) {
            status.setPercentage((double) completedCount / totalStudents * 100);
        }
        return status;
    }

    @Override
    public Page<HomeworkStudent> getHomeworkByStudent(String homeworkId, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<HomeworkStudent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HomeworkStudent::getHomeworkId, homeworkId);
        return homeworkStudentMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
    }

    @Override    // 保存作业学生信息
    public boolean saveAllHomeworkStudent(Homework homework) {
        List<Student> students = classesService.getStudentsByClassId(homework.getClassId());
        for (Student student : students) {
            HomeworkStudent homeworkStudent = new HomeworkStudent();
            homeworkStudent.setId(UUIDUtil.generate(OtherConstants.ID_LENGTH));
            homeworkStudent.setHomeworkId(homework.getId());
            homeworkStudent.setStudentId(student.getId());
            homeworkStudentMapper.insert(homeworkStudent);
        }
        return true;
    }


    @Override
    public HomeworkSatatusVo getHomeworkStatus2(String homeworkId, Integer pageNum, Integer pageSize, String sortType) {
        HomeworkSatatusVo status = new HomeworkSatatusVo();
        status.setHomeworkSatatus(getHomeworkStatus(homeworkId));

        // 4. 查询分页后的学生成绩列表（仅已完成作业的学生）
        Page<StudentScoreVO> page = new Page<>(pageNum, pageSize);
        Page<HomeworkStudent> page2 = new Page<>(pageNum, pageSize);

        // 构建查询条件（已完成作业 + 按成绩排序）
        LambdaQueryWrapper<HomeworkStudent> studentQuery = new LambdaQueryWrapper<>();
        studentQuery.eq(HomeworkStudent::getHomeworkId, homeworkId)
                .isNotNull(HomeworkStudent::getStatus);

        // 设置排序（升序/降序）
        if ("desc".equalsIgnoreCase(sortType)) {
            studentQuery.orderByDesc(HomeworkStudent::getScore);
        } else {
            studentQuery.orderByAsc(HomeworkStudent::getScore);
        }

        // 执行分页查询
        Page<HomeworkStudent> homeworkStudentPage = homeworkStudentMapper.selectPage(page2, studentQuery);
        page.setTotal(page2.getTotal());  //总数
        page.setSize(page2.getSize());  //每页大小
        page.setCurrent(page2.getCurrent());//当前页码
        // 转换为StudentScoreVO（关联学生姓名）
        List<StudentScoreVO> studentScoreList = homeworkStudentPage.getRecords().stream()
                .map(homeworkStudent -> {
                    StudentScoreVO vo = new StudentScoreVO();
                    vo.setStudentId(homeworkStudent.getStudentId());
                    vo.setScore(homeworkStudent.getScore());
                    // 查询学生姓名（实际项目中可能通过关联查询一次性获取）
                    Student student = studentService.getStudentByIdWithLogicalExpire(homeworkStudent.getStudentId());
                    if (student != null) {
                        vo.setStudentName(student.getName());
                    }

                    return vo;
                })
                .collect(Collectors.toList());

        // 设置分页结果
        page.setRecords(studentScoreList);
        status.setStudentPage(page);
        return status;
    }


    @Override
    @Transactional
    public void saveOrUpdateHomeworkStudent(HomeworkStudent homeworkStudent, List<StudentAnswers> studentAnswers) {
        // 处理 homework_student 表（逻辑不变）
        LambdaQueryWrapper<HomeworkStudent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HomeworkStudent::getHomeworkId, homeworkStudent.getHomeworkId())
                .eq(HomeworkStudent::getStudentId, homeworkStudent.getStudentId());
        HomeworkStudent existHomeworkStudent = getOne(queryWrapper);

        if (existHomeworkStudent == null) {         //如果作业学生表没有这个数据，则加入
            save(homeworkStudent);
        } else {
            homeworkStudent.setId(existHomeworkStudent.getId());  //有则修改
            updateById(homeworkStudent);
        }

        // 批量处理 student_answer 表
        for (StudentAnswers answer : studentAnswers) {
            LambdaQueryWrapper<StudentAnswers> answerQueryWrapper = new LambdaQueryWrapper<>();
            answerQueryWrapper.eq(StudentAnswers::getStudentId, answer.getStudentId())
                    .eq(StudentAnswers::getHomeworkId, answer.getHomeworkId())
                    .eq(StudentAnswers::getQuestionId, answer.getQuestionId());
            StudentAnswers existAnswer = studentAnswerMapper.selectOne(answerQueryWrapper);
            if (existAnswer == null) {                //学生没有写这道题，没有则插入
                studentAnswerMapper.insert(answer);
            } else {
                answer.setId(existAnswer.getId());   //有就修改，是否正确，这道题的分数
                studentAnswerMapper.updateById(answer);
            }
        }
    }


//    @Override
//    @Transactional
//    public HomeworkStudentVo getStudentHomeworkByPage(
//            String studentId, String homeworkId, Integer pageNum, Integer pageSize) {
//        // 1. 获取作业基本信息
//        Homework homework = homeworkMapper.selectById(homeworkId);
//        if (homework == null) {
//            throw new OtherException("作业不存在");
//        }
//        // 2. 创建分页对象
//        Page<HomeworkQuestion> page = new Page<>(
//                pageNum == null ? 1 : pageNum,
//                pageSize == null ? 10 : pageSize
//        );
//        // 3. 分页查询作业下的题目
//        LambdaQueryWrapper<HomeworkQuestion> questionQuery = new LambdaQueryWrapper<>();
//        questionQuery.eq(HomeworkQuestion::getHomeworkId, homeworkId);
//        Page<HomeworkQuestion> questionPage = homeworkQuestionMapper.selectPage(page, questionQuery);
//
//        // 4. 提取当前页的题目ID
//        List<String> questionIds = questionPage.getRecords().stream()
//                .map(HomeworkQuestion::getQuestionId)
//                .collect(Collectors.toList());
//
//        // 5. 获取学生对这些题目的答案（批量查询）
//        List<StudentAnswers> studentAnswers = new ArrayList<>();
//        if (!questionIds.isEmpty()) {
//            LambdaQueryWrapper<StudentAnswers> answerQuery = new LambdaQueryWrapper<>();
//            answerQuery.eq(StudentAnswers::getStudentId, studentId)
//                    .eq(StudentAnswers::getHomeworkId, homeworkId)
//                    .in(StudentAnswers::getQuestionId, questionIds);
//            studentAnswers = studentAnswersMapper.selectList(answerQuery);
//        }
//
//        // 6. 将答案转换为Map方便查找
//        Map<String, StudentAnswers> answerMap = studentAnswers.stream()
//                .collect(Collectors.toMap(StudentAnswers::getQuestionId, answer -> answer, (a, b) -> a));
//
//        // 7. 组装返回数据
//        HomeworkStudentVo result = new HomeworkStudentVo();
//        result.setHomeworkId(homeworkId);
//        result.setHomeworkTitle(homework.getHomeworkName());
//        result.setTotalQuestions((int) questionPage.getTotal());
//
//        // 8. 转换题目列表并关联学生答案
//        Page<HomeworkQuestionVO> resultPage = new Page<>(
//                questionPage.getCurrent(),
//                questionPage.getSize(),
//                questionPage.getTotal()
//        );
//
//        List<HomeworkQuestionVO> questionVOs = questionPage.getRecords().stream().map(question -> {
//
//            HomeworkQuestionVO vo = new HomeworkQuestionVO();
//            vo.setQuestionId(question.getQuestionId());
//            vo.setQuestionContent(question.getContent());
//            vo.setQuestionType(question.getType());
//
//            // 设置学生答案（如果有）
//            StudentAnswers answer = answerMap.get(question.getQuestionId());
//            if (answer != null) {
//                vo.setStudentAnswer(answer.getAnswer());
//                vo.setScore(answer.getScore());
//                vo.setIsCorrected(answer.getIsCorrected());
//            }
//
//            return vo;
//        }).collect(Collectors.toList());
//
//        resultPage.setRecords(questionVOs);
//        result.setQuestions(resultPage);
//
//        return result;
//    }
}
